//
//  BVUserInfoViewController.m
//  BuyVegetable
//
//  Created by yushanchang on 16/10/21.
//  Copyright © 2016年 com.yinding. All rights reserved.
//

#import "BVUserInfoViewController.h"
#import "BVModifyNameViewController.h"
#import "BVModifySexViewController.h"
#import "BVModifyMobileViewController.h"
#import "BVModifyBirthViewController.h"
#import "BVModifyAddressViewController.h"
#import "UIImageView+WebCache.h"
#import "BVMineTool.h"
#import "JDStatusBarNotification.h"

#define USER_INFO_CELL_IDENTIFIER @"UserInfoCell"

@interface BVUserInfoViewController ()
<UITableViewDelegate,UITableViewDataSource,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) UIImageView *avatarImageView;
@property (nonatomic, strong) UIImagePickerController *imagePickerController;
@property (nonatomic, strong) BVMineTool *mineTool;

@end

@implementation BVUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"个人资料设置"];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self fetchUserInfo];
}

- (void)fetchUserInfo {
    [self.mineTool fetchUserInfoSuccess:^(){
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self showError:@"加载失败"];
    }];
}

- (UIImageView *)avatarImageView {
    if (!_avatarImageView) {
        _avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
        _avatarImageView.layer.cornerRadius = 25.f;
        _avatarImageView.layer.masksToBounds = YES;
        _avatarImageView.layer.borderWidth = 0;
    }
    [_avatarImageView sd_setImageWithURL: [NSURL URLWithString:self.user.avatar_url] placeholderImage:IMAGE_NAMED(@"icon")];
    return _avatarImageView;
}

#pragma mark - 
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 0 ? 5:2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:USER_INFO_CELL_IDENTIFIER];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:USER_INFO_CELL_IDENTIFIER];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.textLabel setFont:SYSTEM_FONT(16)];
        [cell.textLabel setTextColor:[UIColor BVBaseTextBlackColor]];
        cell.textLabel.text = self.titleArr[indexPath.section][indexPath.row][@"title"];
        [cell.detailTextLabel setFont:SYSTEM_FONT(14)];
        
        if (!((indexPath.section == 0 && indexPath.row == 0) || (indexPath.section == 1 && indexPath.row == 1))) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    }
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.accessoryView.layer.cornerRadius = 25.f;
            cell.accessoryView = self.avatarImageView;
        } else if (indexPath.row == 1){
            cell.detailTextLabel.text = self.user.name;
        } else if (indexPath.row == 2) {
            cell.detailTextLabel.text = self.user.gender == 1 ? @"男":self.user.gender == 2 ? @"女":@"";
        } else if (indexPath.row == 3) {
            cell.detailTextLabel.text = self.user.mobile;
        } else if (indexPath.row == 4) {
            cell.detailTextLabel.text = self.user.birthday;
        }
    } else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            cell.detailTextLabel.text = self.user.address;
        } else if (indexPath.row == 1) {
            cell.detailTextLabel.text = self.user.detail_address;
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            // 设置头像
            [self launchImagePicker];
            
        } else if (indexPath.row == 1) {
            BVModifyNameViewController *modifyName = [[BVModifyNameViewController alloc] init];
            [self.navigationController pushViewController:modifyName animated:YES];
        } else if (indexPath.row == 2) {
            BVModifySexViewController *modifySex = [[BVModifySexViewController alloc] init];
            [self.navigationController pushViewController:modifySex animated:YES];
        } else if (indexPath.row == 3) {
            BVModifyMobileViewController *modifyMobile = [[BVModifyMobileViewController alloc] init];
            [self.navigationController pushViewController:modifyMobile animated:YES];
        } else if (indexPath.row == 4) {
            BVModifyBirthViewController *modifyBirth = [[BVModifyBirthViewController alloc] init];
            [self.navigationController pushViewController:modifyBirth animated:YES];
        }
    } else {
        if (indexPath.row == 0) {
            BVModifyAddressViewController *modifyAddress = [[BVModifyAddressViewController alloc] init];
            [self.navigationController pushViewController:modifyAddress animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return indexPath.section == 0 && indexPath.row == 0 ? 60 : 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 0 ? 5:10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return section == 1 ? 55:0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 1) {
        UIView *footer = [[UIView alloc] init];
        footer.frame = CGRectMake(0, 0, ScreenW, 55);
        UIButton *logout = [[UIButton alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 45)];
        [logout setTitle:@"退出登录" forState:UIControlStateNormal];
        [logout setTitleColor:[UIColor BVBaseOrangeColor] forState:UIControlStateNormal];
        logout.backgroundColor = [UIColor whiteColor];
        [logout addTarget:self action:@selector(logoutClick) forControlEvents:UIControlEventTouchUpInside];
        [footer addSubview:logout];
        return footer;
    }else {
        return [[UIView alloc] init];
    }
}

- (void)logoutClick {
    [self.mineTool logoutSuccess:^(NSString *status) {
        if ([status isEqualToString:@"0"]) {
            [self showSuccess:@"退出成功"];
            [JDStatusBarNotification showWithStatus:@"退出成功" dismissAfter:2.0 styleName:JDStatusBarStyleSuccess];
            [self.user logout];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(NSError *error) {
        [self showError:@"退出失败"];
    }];
}

#pragma mark - 
#pragma mark -
- (void)launchImagePicker {

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"更改头像" message:@"选择头像位置" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *fromCamera = [UIAlertAction actionWithTitle:@"从相机选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePickerController.allowsEditing = YES;
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
    }];
    
    fromCamera.enabled = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    
    UIAlertAction *fromGallery = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:self.imagePickerController animated:YES completion:nil];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    
    [alertController addAction:fromGallery];
    [alertController addAction:fromCamera];
    [alertController addAction:cancel];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -
#pragma mark - ImagePicker Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *userAvatar;
    if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
        userAvatar = [info objectForKey:UIImagePickerControllerOriginalImage];
    } else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        userAvatar = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    [self.hud show:YES];
    [self.mineTool settingUserAvatar:userAvatar success:^{
        [self.hud hide:YES];
        [self showSuccess:@"上传成功"];
        self.avatarImageView.image = userAvatar;
    } failure:^(NSError *error) {
        [self.hud hide:YES];
        [self showError:@"上传失败"];
    }];
}

-(NSArray *)titleArr{
    if (!_titleArr) {
        _titleArr = @[
  @[@{@"title":@"头像"},@{@"title":@"姓名"},@{@"title":@"性别"},@{@"title":@"电话"},@{@"title":@"生日"}],
  @[@{@"title":@"地址"},@{@"title":@"详细地址"}]
  ];
    }
    return _titleArr;
}

- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self;
    }
    return _imagePickerController;
}

- (BVMineTool *)mineTool {
    if (!_mineTool) {
        _mineTool = [[BVMineTool alloc] init];
    }
    return _mineTool;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
